package online.sixfish.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import online.sixfish.common.eunmration.ContentAuditConclusionTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.MessageFormat;
import java.time.LocalTime;
import java.util.Objects;

@Slf4j
@Component
public class ContentAuditUtil {
    static final OkHttpClient HTTP_CLIENT =
            new OkHttpClient().newBuilder().build();

    private static final String URL_PATTERN =
            "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={0}";

    private String token;

    public ContentAuditConclusionTypeEnum audit(String content) throws IOException {
        RequestBody formBody = new FormBody.Builder().add("text", content).build();
        String url = MessageFormat.format(URL_PATTERN, getAccessToken());
        Request request = new Request.Builder()
                .url(url)
                .method("POST", formBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(response.body().string());
        String type = jsonObject.getString("conclusionType");
        ContentAuditConclusionTypeEnum result = ContentAuditConclusionTypeEnum.getById(Integer.parseInt(type));
        return result;
    }

    private String getAccessToken() throws IOException {
        if (Objects.equals(LocalTime.now(), LocalTime.of(2, 0))) {
            token = null;
        }
        if (StringUtils.isNotBlank(token)) {
            return token;
        }
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=16Zhfxqh0i33155ZdcxpggxW&client_secret=y4MyMGzoWhaGxCsicyxAoQQKc3W3tmpF&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = (JSONObject) JSON.parse(response.body().string());
        String accessToken = jsonObject.getString("access_token");
        log.info("请求百度内容审核access_token成功--------->");
        token = accessToken;
        return accessToken;

    }


}
